package com.treetao.union.core.tencent.mp.kit;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.treetao.union.core.exception.DevMException;
import com.treetao.union.core.redis.RedisService;
import com.treetao.union.core.util.HttpKit;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class MpJsticketService {
	private final static String jsticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
	private final static String tencent_mp_jsticket = "tencent_mp_jsticket";

	@Autowired
	private RedisService redisService;
	
	public String getJsticket(String access_token)  throws DevMException{
		if (redisService.hasKey(tencent_mp_jsticket)) {
			String jsticket = redisService.get(tencent_mp_jsticket).toString();
			log.info("从redis中获取jsticket --> " + jsticket);
			return jsticket;
		}
		Map<String, String> params = new HashMap<String, String>();
		params.put("access_token", access_token);
		params.put("type", "jsapi");
		String jsticket = HttpKit.get(jsticket_url, params);
		JSONObject jsonTicket = JSONObject.parseObject(jsticket);
		if (jsonTicket.getIntValue("errcode") == 0) {
			String ticket = jsonTicket.getString("ticket");
			int expires_in = jsonTicket.getIntValue("expires_in");// 单位(秒)
			redisService.set(tencent_mp_jsticket, ticket, expires_in);
			log.info("调用接口获取jsticket并存入到redis中 --> " + ticket);
			return ticket;
		}else {
			throw new DevMException(jsonTicket.getString("errmsg"));
		}
	}
}
